package com.sxmmall.product.service.impl;

import com.sxmmall.common.to.SkuHasStockVo;
import com.sxmmall.common.to.SkuReductionTo;
import com.sxmmall.common.to.SpuBoundsTo;
import com.sxmmall.common.to.es.SkuEsModel;
import com.sxmmall.common.utils.R;
import com.sxmmall.product.entity.*;
import com.sxmmall.product.feign.CouponFeignService;
import com.sxmmall.product.feign.WareFeignService;
import com.sxmmall.product.service.*;
import com.sxmmall.product.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxmmall.common.utils.PageUtils;
import com.sxmmall.common.utils.Query;

import com.sxmmall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /*
     * @Author sxm
     * @Description 服务间事务的一致性
     * @Date 17:16 2021/9/17
     * @Param [spuSaveVo]
     * @return [com.sxmmall.product.vo.SpuSaveVo]
     **/
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        // 1.保存基本信息
        SpuInfoEntity spuInfo = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfo);
        spuInfo.setCreateTime(new Date());
        spuInfo.setUpdateTime(new Date());
        this.saveBatchSpuInfo(spuInfo);

        // 2.保存spu的描述图片
        List<String> decript = spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        Long id = spuInfo.getId();
        spuInfoDescEntity.setSpuId(id);
        spuInfoDescEntity.setDecript(String.join(",", decript));
        this.saveSpuInfoDesc(spuInfoDescEntity);
        // 3.保存spu的图片集
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(spuInfo.getId(), images);
        // 4.保存spu基本属性-规格参数
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntityList = baseAttrs.stream().map(item -> {
            ProductAttrValueEntity attrValueEntity = new ProductAttrValueEntity();
            attrValueEntity.setAttrId(item.getAttrId());
            attrValueEntity.setAttrValue(item.getAttrValues());
            attrValueEntity.setQuickShow(item.getShowDesc());
            attrValueEntity.setSpuId(spuInfo.getId());
            // 属性名称
            AttrEntity byId = attrService.getById(item.getAttrId());
            attrValueEntity.setAttrName(byId.getAttrName());
            return attrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttrValueEntity(productAttrValueEntityList);
        //  保存spu积分信息
        // 5.保存商品的积分
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds, spuBoundsTo);
        spuBoundsTo.setSpuId(spuInfo.getId());
        couponFeignService.saveSpuBounds(spuBoundsTo);
        // 5.1保存skuInfo 基础信息 销售属性
        List<Skus> skus = spuSaveVo.getSkus();
        if (skus.size() > 0 && skus != null) {
            skus.forEach(item -> {
                // 默认展示图片
                String imageDefault = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        imageDefault = image.getImgUrl();
                    }
                }

                SkuInfoEntity skuInfo = new SkuInfoEntity();
                skuInfo.setSkuDefaultImg(imageDefault);
                BeanUtils.copyProperties(item, skuInfo);
                skuInfo.setBrandId(spuInfo.getBrandId());
                skuInfo.setCatalogId(spuInfo.getCatalogId());
                skuInfo.setSaleCount(0L);
                skuInfo.setSpuId(spuInfo.getId());
                skuInfoService.saveSkuInfo(skuInfo);

                Long skuId = skuInfo.getSkuId();
                List<SkuImagesEntity> skuImagesEntityList = item.getImages().stream().map(image -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setDefaultImg(image.getDefaultImg());
                    skuImagesEntity.setImgUrl(image.getImgUrl());
                    skuImagesEntity.setSkuId(skuId);
                    return skuImagesEntity;
                }).filter(image -> StringUtils.isNotEmpty(image.getImgUrl())).collect(Collectors.toList());
                // 5.2保存skuImage 信息
                skuImagesService.saveSkuImages(skuImagesEntityList);
                // 5.3保存sku 的销售属性信息
                List<Attr> attrs = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntityList = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity saleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, saleAttrValueEntity);
                    saleAttrValueEntity.setSkuId(skuId);
                    return saleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntityList);
                // 5.3保存sku的有优惠信息
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                    R r = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r.getCode() != 0) {
                        log.info("调用远程服务 - 保存sku优惠信息失败");
                    }
                }
            });
        }
    }

    public void saveBatchSpuInfo(SpuInfoEntity spuInfo) {
        save(spuInfo);
    }

    @Override
    public void saveSpuInfoDesc(SpuInfoDescEntity spuInfoDescEntity) {
        spuInfoDescService.save(spuInfoDescEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> query = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            query.and((w) -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId)) {
            query.eq("catalog_id", catelogId);
        }

        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            query.eq("publish_status", status);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId)) {
            query.eq("brand_id", brandId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                query
        );

        return new PageUtils(page);
    }


    @Override
    public void spuUp(Long spuId) {
        List<SkuEsModel> skuEsModelList = new ArrayList<>();


        // 查询当前sku所有可以用来检索额度规格参数
        List<ProductAttrValueEntity> baseValues = productAttrValueService.baseAttrListForSpu(spuId);
        List<Long> attrIds = baseValues.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        List<Long> searchAttrIds = attrService.selectSearchAttrs(attrIds);
        Set<Long> idSet = new HashSet<>(searchAttrIds);
        List<SkuEsModel.Attrs> attrsList = baseValues.stream()
                .filter(item -> idSet.contains(item.getAttrId()))
                .map(item -> {
                    SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
                    BeanUtils.copyProperties(item, attrs);
                    return attrs;
                }).collect(Collectors.toList());

        // 1.获取spu对应的sku所有信息,品牌名称
        List<SkuInfoEntity> skus = skuInfoService.getSkuBySpuId(spuId);
        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        // 发送请求 调用远程ware服务 , 查询是否有库存
        Map<Long, Boolean> skuHasStockMap = new HashMap<>();
        try {
            R<List<SkuHasStockVo>> skuHasStock = wareFeignService.getSkuHasStock(skuIds);
            skuHasStockMap = skuHasStock.getData().stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        } catch (Exception e) {
            log.error("库存服务调用异常{}", e.getMessage());
        }

        // 2.封装每个sku的信息
        Map<Long, Boolean> finalSkuHasStockMap = skuHasStockMap;
        skus.stream().map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, skuEsModel);
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());

            // hasStock,hotScore
            skuEsModel.setHasStock(finalSkuHasStockMap != null ? finalSkuHasStockMap.get(sku.getSkuId()) : true);

            // 设置热度评分
            skuEsModel.setHotScore(0L);
            // 获取品牌,分类名字
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            skuEsModel.setBrandName(brandEntity.getName());
            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            // 设置检索属性
            skuEsModel.setAttrs(attrsList);
            return skuEsModel;
        }).collect(Collectors.toList());

        // 将数据发送给 es 进行保存

    }
}